/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dailydev.wave.robot.spring;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dailydev.wave.robot.IRobot;
import org.dailydev.wave.robot.RobotException;
import org.dailydev.wave.robot.serializer.ISerializer;
import org.dailydev.wave.robot.serializer.OperationMessageBundleSerializer;
import org.dailydev.wave.robot.serializer.RobotMessageBundleSerializer;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.impl.OperationMessageBundle;
import com.google.wave.api.impl.RobotMessageBundleImpl;

/**
 * 
 * @author Roman Bosak, DailyDev.org
 */
public class RobotController implements Controller {

    /**
     * {@link RobotController}'s logger
     */
    private static Logger log = Logger.getLogger(RobotController.class.getName());

    /**
     * Logger for request and response payload
     */
    private static Logger payloadLog = Logger.getLogger("robot.payload.events");

    /**
     * Serialiser and deserialiser of message payload.
     */
    protected ISerializer<RobotMessageBundle> messageBundleSerializer;

    /**
     * Serialiser and deserialiser of message payload.
     */
    protected ISerializer<OperationMessageBundle> operationsSerializer;

    /**
     * Reference to served robot
     */
    protected IRobot robot;

    /**
     * 
     */
    public RobotController() {
        super();

        messageBundleSerializer = new RobotMessageBundleSerializer();
        operationsSerializer = new OperationMessageBundleSerializer();
    }

    /** {@inheritDoc} */
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = getRequestBody(request);

        if (payloadLog.isLoggable(Level.FINEST)) {
            payloadLog.finest("REQUEST: >>>" + requestBody + "<<<");
        }

        RobotMessageBundle bundle = null;
        try {
            bundle = messageBundleSerializer.deserialize(requestBody);
        } catch (RobotException e) {
            log.log(Level.SEVERE, "400 - Bad Request >>>" + payloadLog + "<<<", e);
            if (payloadLog.isLoggable(Level.FINEST)) {
                payloadLog.finest("RESPONSE: 400 Bad Request >>> " + e.getMessage());
            }
            response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        if (bundle != null) {
            try {
                robot.processEvents(bundle);

                OperationMessageBundle operations = ((RobotMessageBundleImpl) bundle).getOperations();
                operations.setVersion(robot.getRobotVersion());

                String responseBody = operationsSerializer.serialize(operations);

                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().write(responseBody);

                response.setStatus(HttpURLConnection.HTTP_OK);

                if (payloadLog.isLoggable(Level.FINEST)) {
                    payloadLog.finest("RESPONSE: 200 OK >>>" + responseBody + "<<<");
                }
            } catch (RobotException e) {
                log.log(Level.SEVERE, "500 - Internal Server Error", e);
                if (payloadLog.isLoggable(Level.FINEST)) {
                    payloadLog.finest("RESPONSE: 500 Internal Server Error >>> " + e.getMessage());
                }
                response.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        }

        return null;
    }

    /**
     * @param request
     * @return
     * @throws IOException
     */
    protected String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder body = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            body.append(line);
        }
        return body.toString();
    }

    /**
     * @return the serializer
     */
    public ISerializer<RobotMessageBundle> getMessageBundleSerializer() {
        return messageBundleSerializer;
    }

    /**
     * @param serializer
     *            the serializer to set
     */
    public void setMessageBundleSerializer(ISerializer<RobotMessageBundle> serializer) {
        this.messageBundleSerializer = serializer;
    }

    /**
     * @return the robot
     */
    public IRobot getRobot() {
        return robot;
    }

    /**
     * @param robot
     *            the robot to set
     */
    public void setRobot(IRobot robot) {
        this.robot = robot;
    }

}
